/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.migrate;

import com.wtkj.vo.dzzf.base.kfwd.Account;
import com.wtkj.vo.dzzf.base.kfwd.FundAccount;
import com.wttech.dzzf.process.dao.ImportHisDataDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 资金账户信息合并
 *
 * @author MaShibo
 * @date 2017/12/10.
 */
@Service
public class MergeFundAccountService {

	private static final Logger LOGGER = LoggerFactory.getLogger(MergeFundAccountService.class);

	@Resource
	private ImportHisDataDao importHisDataDao;

	@Transactional(rollbackFor = Exception.class)
	public void process(List<FundAccount> fundAccounts) {
		if (fundAccounts.isEmpty()){
			return;
		}
		//最新办理账户
		FundAccount first = fundAccounts.get(0);
		String finalFundAccountId = first.getFundAccountId();
		List<Account> accounts = importHisDataDao.queryAccountsByFundAccountId(finalFundAccountId);
		if (accounts.isEmpty()) {
			LOGGER.error("资金账户【{}】，没有对应的业务账户信息", finalFundAccountId);
			return;
		}
		String finalAccountId = accounts.get(0).getAccountId();

		for (int i = 1; i < fundAccounts.size(); i++) {
			FundAccount fundAccount = fundAccounts.get(i);
			List<Account> accountList = importHisDataDao.queryAccountsByFundAccountId(fundAccount.getFundAccountId());
			accountList.forEach(account -> {
				//更新AC_CARDINFO的ACCOUNTID
				importHisDataDao.updateCardInfoAccountId(finalAccountId, account.getAccountId());
				//更新AC_ACCOUNT的FUNDACCOUNTID
				importHisDataDao.updateAccountFundAccountId(finalFundAccountId, account.getFundAccountId());
				//删除AC_ACCOUNT
				importHisDataDao.deleteAccount(account.getAccountId());
				//删除AC_ACCOUNTOPT
				importHisDataDao.deleteAccountOpt(account.getAccountId());
			});
			//删除
			importHisDataDao.deleteFundAccount(fundAccount.getFundAccountId());
		}


	}

}
